/**
 * @Author: ls <ls-mac>
 * @Date:   2019-08-13 17:59:28
 * @Last modified by:   ls-mac
 * @Last modified time: 2020-03-13 10:07:40
 */
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import common from 'utils/common';
import {
  Alert,
  Row,
  Col,
  Card,
  Checkbox,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Popover,
  Popconfirm,
  TimePicker,
  Table,
  Tag,
  Modal,
  message,
  Badge,
  Divider,
  Upload,
} from 'antd';
import SimpleTable from 'components/SimpleTable';
import { relative } from 'path';
import styles from './enterprise.less';

import PageHeaderLayout from '../../layouts/PageHeaderLayout';

const FormItem = Form.Item;

const CheckboxGroup = Checkbox.Group;

const InputGroup = Input.Group;

const TextArea = Input.TextArea;

const { MonthPicker, RangePicker, WeekPicker } = DatePicker;

const { Option } = Select;

const CreateForm = Form.create()(prop => {
  const {
    state,
    form,
    props,
    handleCancel,
    onSelect,
    onChangeH,
    renderOptionsH,
    uploadChange,
  } = prop;
  const { modalVisible, result, contractId, display, uploadfaillist, uploadsuccess } = state;
  const { getFieldDecorator } = form;
  const { dispatch } = props;

  const detailInfo = {};
  const beforeUpload = () => {
    let re = true;
    if (!contractId) {
      message.info('请选择合同');
      re = false;
    }
    return re;
  };

  return (
    <Modal
      title="报告上传"
      visible={modalVisible}
      onOk={() => handleCancel()}
      onCancel={() => handleCancel()}
      className=""
      okText="关闭"
      width="540px"
      destroyOnClose
    >
      <Form layout="inline">
        <Row>
          <Col md={12} sm={24}>
            <FormItem label="企业名称">
              {getFieldDecorator('companyId', {
                rules: [{ required: true, message: '请输入企业名称' }],
              })(
                <Select
                  showSearch
                  placeholder="输入企业名称查询"
                  style={{ width: 150 }}
                  optionFilterProp="children"
                  onChange={onSelect}
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {result}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={12} sm={24}>
            <FormItem label="合同名称">
              {getFieldDecorator('contractId', {
                rules: [{ required: true, message: '请选择合同名称' }],
              })(
                <Select
                  placeholder="请选择"
                  style={{ width: 150 }}
                  onSelect={onChangeH}
                  autoClearSearchValue
                  allowClear
                >
                  {renderOptionsH()}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col md={24} sm={24}>
            <FormItem label="上传报告">
              {getFieldDecorator('aaa', {
                rules: [{ required: true, message: '请上传报告' }],
              })(
                <Upload
                  action="https://service-api.lisonhealth.com/report/upload"
                  headers={{ Authorization: localStorage.getItem('authorization-token') }}
                  data={{ contractId }}
                  beforeUpload={beforeUpload}
                  onChange={uploadChange}
                >
                  <Button style={{ width: 150 }}>
                    <Icon type="upload" /> 上传报告
                  </Button>
                </Upload>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row style={{ display }}>
          <Col md={24} sm={24} style={{ marginTop: 10 }}>
            <span style={{ color: 'red' }}>上传成功条数:&#12288;</span>
            {uploadsuccess}
          </Col>
        </Row>
        <Row style={{ display }}>
          <Col md={24} sm={24} style={{ marginTop: 10 }}>
            <span style={{ color: 'red' }}>上传失败文件:&#12288;</span>
            {uploadfaillist}条
          </Col>
        </Row>
      </Form>
    </Modal>
  );
});

@connect(({ packageList, contractList, companyStorePage, orderList, orderReport, loading }) => ({
  packageList,
  contractList,
  companyStorePage,
  orderList,
  orderReport,
  loading: loading.models.packageList,
}))
@Form.create()
export default class TableList extends PureComponent {
  state = {
    modalVisible: false,
    result: [], // 企业名称 自动匹配结果
    companyId: '',
    contractId: '',
    display: 'none',
    uploadfaillist: '',
    uploadsuccess: 0,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'orderReport/fetch',
      payload: {
        name: '',
        pageIndex: '1',
        pageSize: '10',
      },
    });

    // 查询公司
    dispatch({
      type: 'companyStorePage/companyList',
      payload: {
        name: '',
      },
      callback: res => {
        const newList = res.data.map(v => {
          return <Option value={v.id}>{v.name}</Option>;
        });
        this.setState({
          dataSource: newList,
          result: newList,
        });
      },
    });
  }

  onSelect = v => {
    const { dispatch } = this.props;

    // 查询合同
    dispatch({
      type: 'contractList/getList',
      payload: { companyId: v },
    });

    this.setState({
      companyId: v,
    });
  };

  onChangeH = v => {
    this.setState({
      contractId: v,
    });
  };

  // 分页
  handleStandardTableChange = pagination => {
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      const params = {
        pageIndex: pagination.current,
        pageSize: pagination.pageSize,
        name: values.name,
      };

      dispatch({
        type: 'orderReport/fetch',
        payload: params,
      });
    });
  };

  // 重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    dispatch({
      type: 'orderReport/fetch',
      payload: {
        name: '',
        pageIndex: '1',
        pageSize: '10',
      },
    });
  };

  handleDelete = record => {
    const { dispatch } = this.props;
    dispatch({
      type: 'orderReport/reportDelete',
      payload: {
        id: record.id,
      },
      callback: res => {
        if (res.success) {
          message.success('删除成功');
        } else {
          message.info(res.errorDesc);
        }
        this.handleFormReset();
      },
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
      };
      const params = {
        pageIndex: 0,
        pageSize: 10,
        name: values.name,
      };
      dispatch({
        type: 'orderReport/fetch',
        payload: params,
      });
    });
  };

  handleCancel = () => {
    this.setState({
      modalVisible: false,
    });
  };

  handleAdd = () => {
    this.setState({
      contractId: '',
      modalVisible: true,
    });
  };

  uploadChange = info => {
    if (info.file.status === 'done') {
      const { success } = info.file.response;
      if (success) {
        const {
          file: {
            response: { data },
          },
        } = info;
        if (data) {
          const { errorList, upLoadFailList, succeccList } = data;
          const newList = [...errorList, ...upLoadFailList];
          if (newList.length) {
            const list = newList.map(v => {
              return <Tag color="red">{v}</Tag>;
            });
            this.setState({
              uploadfaillist: list,
            });
          } else {
            message.success(`导入成功.`);
          }
          this.setState({
            display: 'block',
            uploadsuccess: succeccList.length,
          });
        }

        this.handleFormReset();
      } else {
        message.success(`导入失败.`);
      }
    } else if (info.file.status === 'error') {
      message.error(`上传文件失败.`);
    }
  };

  reColumns = () => {
    return [
      {
        title: '企业名称',
        dataIndex: 'companyName',
      },
      {
        title: '合同',
        dataIndex: 'contractTitle',
      },
      {
        title: '员工',
        dataIndex: 'employeeName',
      },
      {
        title: '证件号',
        dataIndex: 'identityNo',
      },
      {
        title: '家属姓名',
        dataIndex: 'familyName',
      },
      {
        title: '家属证件',
        dataIndex: 'familyIdentityNo',
      },
      {
        title: '体检报告',
        dataIndex: 'url',
        render: (v, r) => (
          <a href={v} download={r.title}>
            点击查看
          </a>
        ),
      },
      {
        title: '操作',
        render: (val, record) => (
          <Popconfirm title="确认删除?" onConfirm={() => this.handleDelete(record)}>
            <a>删除</a>
          </Popconfirm>
        ),
      },
    ];
  };

  renderSearchForm = () => {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row
          gutter={{
            md: 8,
            lg: 24,
            xl: 48,
          }}
        >
          <Col md={8} sm={24}>
            <FormItem label="企业名称">
              {getFieldDecorator('name')(<Input style={{ width: '100%' }} placeholder="" />)}
            </FormItem>
          </Col>
          <Col md={16} sm={24}>
            <div
              style={{
                overflow: 'hidden',
                height: '40px',
                lineHeight: '40px',
              }}
            >
              <span
                style={{
                  float: 'right',
                }}
              >
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
                <Button
                  style={{
                    marginLeft: 8,
                  }}
                  onClick={this.handleFormReset}
                >
                  重置
                </Button>
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };

  renderOptionsH = () => {
    const {
      contractList: { list },
    } = this.props;
    const options = list.map(v => (
      <Option key={v.id} value={v.id}>
        {v.title}
      </Option>
    ));
    return options;
  };

  render() {
    const columns = this.reColumns();
    const {
      orderReport: { data },
      loading,
    } = this.props;

    const { modalVisible, companyId } = this.state;

    return (
      <PageHeaderLayout>
        <Card bordered={false} style={{ paddingBottom: '20px' }}>
          <div>
            <div className={styles.tableListForm}>{this.renderSearchForm()}</div>
            <div>
              <Button
                type="primary"
                icon="plus"
                onClick={this.handleAdd}
                style={{ marginRight: 10 }}
              >
                报告上传
              </Button>
            </div>
            <SimpleTable
              selectedRows={false}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={false}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <CreateForm {...this} />
      </PageHeaderLayout>
    );
  }
}
